import {
  Entity,
  Column,
  ManyToMany,
  JoinTable,
  PrimaryColumn,
  BeforeUpdate,
  AfterUpdate,
  AfterInsert,
  BeforeInsert,
} from 'typeorm';
import { v4 as uuidv4 } from 'uuid';
import { UsersEntity } from '../../user/entities/user.entity';
import { DepartmentEntity } from '../../department/entities/department.entity';
import { AccessEntity } from '../../access/entities/access.entity';
import * as moment from 'moment';

@Entity({ name: 'role' })
export class RoleEntity {
  @PrimaryColumn()
  id: string = uuidv4();

  @Column({ type: 'varchar', length: 30 })
  rolename: string;

  @ManyToMany(() => UsersEntity, (user) => user.roles, {
    cascade: true,
    onDelete: 'CASCADE',
  })
  users: UsersEntity[];

  @ManyToMany(() => DepartmentEntity, (department) => department.roles)
  department: DepartmentEntity[];

  @ManyToMany(() => AccessEntity, (access) => access.roles, {
    cascade: true,
    onDelete: 'CASCADE',
  })
  @JoinTable({ name: 'role_access' })
  access: AccessEntity[];

  @Column({ type: 'varchar', nullable: true })
  created_at: string;

  @Column({ type: 'varchar', nullable: true })
  updated_at: string;

  @BeforeInsert()
  createDates() {
    this.created_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }

  @BeforeUpdate()
  updateDates() {
    this.updated_at = moment().format('YYYY-MM-DD HH:mm:ss');
  }
}
